from fastapi import APIRouter, Request, Body
from pydantic import BaseModel
from finance.python.services import budget_service
from finance.python.middleware.auth import token_required
from finance.python.middleware.logging import log_required
from typing import List

# 创建路由器
budget_router = APIRouter(
    prefix="/api",
    tags=["budget"]
)

@budget_router.get("/get_budgets", summary="获取预算列表")
@token_required
@log_required
async def get_budgets(request: Request):
    """
    获取用户的预算列表
    :param request: 请求对象
    """
    user_id = request.state.user_id
    return await budget_service.get_budgets(user_id)

@budget_router.post("/add_budget", summary="添加预算")
@token_required
@log_required
async def add_budget(request: Request, 
                    category: str = Body(...),
                    amount: float = Body(...),
                    description: str = Body(None)):
    """
    添加新预算
    :param request: 请求对象
    :param category: 预算类别
    :param amount: 预算金额
    :param description: 预算描述
    """
    user_id = request.state.user_id
    return await budget_service.add_budget(
        user_id,
        category,
        amount,
        description
    )

@budget_router.put("/update_budget", summary="更新预算")
@token_required
@log_required
async def update_budget(request: Request,
                       budget_id: int = Body(...),
                       category: str = Body(...),
                       amount: float = Body(...),
                       description: str = Body(None)):
    """
    更新预算信息
    :param request: 请求对象
    :param budget_id: 预算ID
    :param category: 预算类别
    :param amount: 预算金额
    :param description: 预算描述
    """
    user_id = request.state.user_id
    return await budget_service.update_budget(
        user_id,
        budget_id,
        category,
        amount,
        description
    )

# 添加请求体模型
class DeleteBudgetRequest(BaseModel):
    budget_id: int

@budget_router.delete("/delete_budget", summary="删除预算")
@token_required
@log_required
async def delete_budget(request: Request, body: DeleteBudgetRequest):
    """
    删除预算
    :param request: 请求对象
    :param body: 删除预算请求体
    """
    user_id = request.state.user_id
    return await budget_service.delete_budget(
        user_id,
        body.budget_id
    )

class BudgetOrder(BaseModel):
    id: int
    sort_order: int

class UpdateBudgetOrderRequest(BaseModel):
    orders: List[BudgetOrder]

@budget_router.put("/update_budget_order", summary="更新预算排序")
@token_required
@log_required
async def update_budget_order(request: Request, body: UpdateBudgetOrderRequest):
    """
    更新预算排序
    :param request: 请求对象
    :param body: 更新预算排序请求体
    """
    user_id = request.state.user_id
    return await budget_service.update_budget_order(
        user_id,
        [order.dict() for order in body.orders]
    )